import 'dart:async';
import 'dart:io';

import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart'
    as select;
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/log.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/cupertino.dart';

import '../pages/login/select_role_page.dart';
import '../push/chat_house_push.dart';
import 'api_host.dart';

enum Status {
  success, // 请求&业务成功
  businessError, // 请求成功  but 业务失败
  systemError // 请求失败
}

Dio initDio() {
  //获取自己输入保存了的Host
  String inputHost = SpUtil.getString(Keys.INPUT_HOST);
  if (inputHost.isEmpty) {
    //获取选中的环境类型 默认选中的单选框的值 0测试 1预发布 2生产
    int typeValue = ApiHost.getDefaultSelectValue();
    inputHost = ApiHost.getHostFromValue(typeValue);
  }
  BaseOptions _baseOptions = BaseOptions(
      baseUrl: inputHost, connectTimeout: const Duration(seconds: 30));
  Dio dio = Dio(_baseOptions);
  dio.options.responseType = ResponseType.json;
  dio.interceptors.add(HttpLog());
  dio.options.headers.addAll({"Content-type": "application/json"});

  return dio;
}

Dio initProxyDio(String proxy) {
  //获取自己输入保存了的Host
  String inputHost = SpUtil.getString(Keys.INPUT_HOST);
  if (inputHost.isEmpty) {
    //获取选中的环境类型 默认选中的单选框的值 0测试 1预发布 2生产
    int typeValue = ApiHost.getDefaultSelectValue();
    inputHost = ApiHost.getHostFromValue(typeValue);
  }
  BaseOptions _baseOptions = BaseOptions(
      baseUrl: inputHost, connectTimeout: const Duration(seconds: 30));
  Dio dio = Dio(_baseOptions);
  dio.options.responseType = ResponseType.json;
  dio.options.headers.addAll({"Content-type": "application/json"});
  dio.interceptors.add(HttpLog());
  (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
      (client) {
    //这一段是解决安卓https抓包的问题
    client.badCertificateCallback =
        (X509Certificate cert, String host, int port) {
      return Platform.isAndroid;
    };
    client.findProxy = (uri) {
      return proxy;
      // return "PROXY 192.168.3.15:8888";
    };
  };
  return dio;
}

class Net {
  // 单例模式固定格式
  Net._();

  // 单例模式固定格式
  static Net? _instance;

  // 单例模式固定格式
  static Net getInstance() {
    _instance ??= Net._();
    return _instance!;
  }

  Dio dio = initDio();

  setDio(String proxy) {
    dio = initProxyDio(proxy);
  }

  clearProxyDio() {
    dio = initDio();
  }

  Future<Response?> requestApi(String method, String path, dynamic data,
      {Map<String, dynamic>? queryParameters,
      bool isUrlencodedType = false}) async {
    // final ConnectivityResult conneResult =
    //     await Connectivity().checkConnectivity();
    // if (conneResult == ConnectivityResult.none) {
    //   ToastUtil.showToast('請檢查網絡或稍後重試');
    // }

    Response? result;
    //獲取token
    String token = SpUtil.getString(Keys.token);
    if (token.isNotEmpty) {
      dio.options.headers.addAll({"Authorization": token});
    }

    if (isUrlencodedType) {
      dio.options.headers
          .addAll({"Content-type": "application/x-www-form-urlencoded"});
    } else {
      dio.options.headers.addAll({"Content-type": "application/json"});
    }

    if (Platform.isAndroid) {
      dio.options.headers.addAll({"deviceType": "android"});
    } else if (Platform.isIOS) {
      dio.options.headers.addAll({"deviceType": "ios"});
    }

    try {
      if (method == 'get') {
        result = await dio.get(
          path,
          queryParameters: data,
        );
      } else if (method == 'post') {
        result =
            await dio.post(path, data: data, queryParameters: queryParameters);
      } else if (method == 'put') {
        result =
            await dio.put(path, data: data, queryParameters: queryParameters);
      }
      return result;
    } on DioError catch (e) {
      var msg = e.response?.data["msg"];
      var code = e.response?.data["code"];
      if (msg != null) {
        ToastUtil.showToast(msg);
      }
      //請求異常的提示
      if (e.response == null) {
        // ToastUtil.showToast("請求異常：${e.message}");
      }
      debugPrint(
          "-- - - - - - - - -DioErrorggg:${e.toString()},code:${e.toString()} path = $path");
      return Future.error(e);
    } finally {}
  }

  /// restful post form 表单提交操作
  Future<Response?> postForm(
    String path, {
    BuildContext? context,
    Map<String, dynamic>? queryParameters,
    FormData? params,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    // final ConnectivityResult conneResult =
    //     await Connectivity().checkConnectivity();
    // if (conneResult == ConnectivityResult.none) {
    //   ToastUtil.showToast('請檢查網絡或稍後重試');
    // }

    //获取自己输入保存了的Host
    String inputHost = SpUtil.getString(Keys.INPUT_HOST);
    if (inputHost.isEmpty) {
      //获取选中的环境类型 默认选中的单选框的值 0测试 1预发布 2生产
      int typeValue = ApiHost.getDefaultSelectValue();
      inputHost = ApiHost.getHostFromValue(typeValue);
    }

    Dio dio = Dio(BaseOptions(
        baseUrl: inputHost,
        connectTimeout: const Duration(seconds: 15),
        receiveTimeout: const Duration(seconds: 15)));

    //獲取token
    String token = SpUtil.getString(Keys.token);
    if (token.isNotEmpty) {
      dio.options.headers.addAll({"Authorization": token});

      if (Platform.isAndroid) {
        dio.options.headers.addAll({"deviceType": "android"});
      } else if (Platform.isIOS) {
        dio.options.headers.addAll({"deviceType": "ios"});
      }
    }
    try {
      Response<String> response =
          await dio.post(path, queryParameters: queryParameters, data: params);
      return response;
    } on DioError catch (e) {
      debugPrint("DioError:${e.toString()},code:${e.toString()} path = $path");
      var msg = e.response?.data["msg"];
      var code = e.response?.data["code"];
      if (msg != null) {
        ToastUtil.showToast(msg);
      }
      //請求異常的提示
      if (e.response == null) {
        // ToastUtil.showToast("請求異常：${e.message}");
      }
      return Future.error(e);
    } finally {}
  }
}

class HttpLog extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    debugPrint("\n --------- Request---------");
    // debugPrint("Request_BaseUrl:${options.baseUrl}");
    debugPrint("Request_Path:${options.path}");
    // debugPrint("Request_Method:${options.method}");
    // debugPrint("Request_ConnectTimeout:${options.connectTimeout}");
    debugPrint("请求头:${options.headers}");
    debugPrint("请求参数:${options.data.toString()}");
    debugPrint("Request_QueryParameters:${options.queryParameters}");

    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    debugPrint("--请求结果--:${response.toString()}");

    if (response.statusCode == 200 || response.statusCode == 201) {
      var code = response.data["code"];
      String? msg = response.data["msg"];
      LogUtil.d("--请求code--：$code $msg");
      if (code != 200) {
        if (code == 401) {
          Obj.dismissLoading();
          ToastUtil.showToast("登錄已失效，請重新登錄哦");
          SpUtil.onClearClear();
          //初始化極光
          ChatHousePush.instance.initPlatformState();
          Get.offAll(const SelectRolePage());
          return;
        }
        String path = response.requestOptions.path;
        if ((msg ?? "").isNotEmpty && !path.contains("isTourist")) {
          ToastUtil.showToast(msg);
        }
        Obj.dismissLoading();
      }
    }
    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    debugPrint("--请求出错--:${err.message},${err.response}");
    if (err.message == null && err.response == null) {
    } else {
      // ToastUtil.showToast("請求異常：${err.response?.statusCode}");
    }
    super.onError(err, handler);
  }
}

class ResponseResult extends Object {
  var code;
  var msg;
  var data;
}
